<template>
	<view class="page-container">
		<u-navbar bgColor="#F5F9FC" :placeholder="true" :border="true" height="48px">
			<view slot="left" class="navbar-left">
				<navigator url="/pageNew/salary/salary" class="back-button">
					<view class="nav-back-content">
						<u-icon color="#1e88e5" name="arrow-left" size="20"></u-icon>
						<text class="nav-title">工资项自定义配置</text>
					</view>
				</navigator>
			</view>
		</u-navbar>

		<view class="config-desc">
			<text>以下为工资项，可根据企业需求调整启用状态</text>
		</view>

		<view class="field-list">
			<view class="field-item" v-for="field in salaryFields" :key="field.id">
				<view class="field-info">
					<view class="field-name">
						{{ field.fieldName }}
						<text class="field-tag" v-if="field.fieldType === 1">
							<u-icon name="lock" size="10" class="tag-icon"></u-icon>
							系统内置
						</text>
						<text class="field-tag custom-tag" v-else>
							<u-icon name="edit-pen" size="10" class="tag-icon"></u-icon>
							自定义
						</text>
					</view>
				</view>

				<view class="field-actions">
					<u-switch v-model="field.isEnabled" @change="handleStatusChange(field.id)"></u-switch>
					<view class="action-icons">
						<u-icon name="edit-pen" size="20" color="#6b7280" @click="editField(field)"></u-icon>
						<u-icon name="trash" size="20" color="#ff4d4f" @click="deleteField(field.id)"></u-icon>
					</view>
				</view>
			</view>
		</view>

		<view class="add-btn-container">
			<view class="add-btn" @click="addCustomField">
				<u-icon name="plus" size="20" color="#ffffff"></u-icon>
				<text class="add-btn-text">添加工资项</text>
			</view>
		</view>

		<u-popup :show="showFieldDialog" :round="10" mode="center" @close="closePopup" @open="openPopup">
			<view class="popup-content">
				<view class="popup-title">
					<text>{{ currentField.id ? '编辑工资项' : '添加工资项' }}</text>
				</view>

				<view class="form-container">
					<view class="form-item">
						<text class="form-label">工资项名称</text>
						<input type="text" v-model="currentField.fieldName" placeholder="请输入工资项名称"
							class="form-input"></input>
					</view>

					<view class="form-item">
						<text class="form-label">是否启用</text>
						<u-switch v-model="currentField.isEnabled" @change="() => {}"></u-switch>
					</view>
				</view>

				<view class="popup-actions">
					<view class="btn-cancel" @click="closePopup">取消</view>
					<view class="btn-submit" @click="saveField">确定</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				companyInfo: uni.getStorageSync('companyInfo'),
				http: uni.$u.http, // 统一请求实例
				salaryFields: [],
				currentField: {
					fieldName: '',
					isEnabled: true,
					fieldType: 2 // 默认自定义
				},
				showFieldDialog: false,
				pageParams: {
					pageNum: 1,
					pageSize: 10
				}
			};
		},
		computed: {
			// 获取公司ID（优先缓存，兜底默认值）
			companyId() {
				return this.companyInfo.id || '1986303016356728834';
			}
		},
		onLoad() {
			// 校验公司ID
			if (!this.companyId) {
				uni.showToast({
					title: '请先选择公司',
					icon: 'none'
				});
				uni.navigateBack();
				return;
			}
			// 页面加载时获取工资项列表
			console.log('当前公司ID:', this.companyId);
			this.getSalaryFields();
		},
		methods: {
			// 获取工资项列表（带公司ID，适配后端返回格式）
			async getSalaryFields() {
				try {
					const res = await this.http.get('/VipSalaryItem/list', {
						params: {
							companyId: this.companyId, // 关键：传递公司ID
							pageNum: this.pageParams.pageNum,
							pageSize: this.pageParams.pageSize
						}
					});

					// 适配后端返回格式：code=200，data.data是工资项数组
					if (res.code === 200 && res.data?.data) {
						// 转换后端数据为前端需要的格式
						this.salaryFields = res.data.data.map(item => ({
							id: item.id,
							fieldName: item.itemName,
							fieldType: item.isSystem, // 1-系统内置，0-自定义（后端isSystem存储1/0）
							isEnabled: item.isEnabled === 1 // 后端1=启用，0=禁用
						}));
					} else {
						uni.showToast({
							title: '加载失败：' + (res.msg || '未知错误'),
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取工资项列表失败', error);
					uni.showToast({
						title: '网络错误，加载失败',
						icon: 'none'
					});
				}
			},

			// 添加工资项（保持原有逻辑）
			addCustomField() {
				this.currentField = {
					fieldName: '',
					isEnabled: true,
					fieldType: 2 // 自定义
				};
				this.showFieldDialog = true;
			},

			// 编辑工资项（统一用this.http，适配后端返回格式）
			async editField(field) {
				try {
					const res = await this.http.get(`/VipSalaryItem/${field.id}`, {
						params: {
							companyId: this.companyId
						} // 传递公司ID
					});
					// 适配后端返回格式
					if (res.code === 200 && res.data) {
						const item = res.data;
						this.currentField = {
							id: item.id,
							fieldName: item.itemName,
							isEnabled: item.isEnabled === 1,
							fieldType: item.isSystem
						};
						this.showFieldDialog = true;
					} else {
						uni.showToast({
							title: '获取详情失败：' + (res.msg || '未知错误'),
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取工资项详情失败', error);
					uni.showToast({
						title: '获取详情失败',
						icon: 'none'
					});
				}
			},

			// 保存工资项（统一用this.http，传递公司ID）
			async saveField() {
				if (!this.currentField.fieldName.trim()) {
					uni.showToast({
						title: '请输入工资项名称',
						icon: 'none'
					});
					return;
				}

				// 校验名称重复（排除当前编辑项）
				const isDuplicate = this.salaryFields.some(item =>
					item.id !== this.currentField.id && item.fieldName === this.currentField.fieldName
				);
				if (isDuplicate) {
					uni.showToast({
						title: '工资项名称已存在',
						icon: 'none'
					});
					return;
				}

				// 构造后端需要的数据格式（与VipSalaryItemEntity对齐）
				const formData = {
					itemName: this.currentField.fieldName,
					isEnabled: this.currentField.isEnabled ? 1 : 0,
					isSystem: this.currentField.fieldType, // 1-系统内置，2-自定义（后端存0/1，这里转换为0）
					companyId: this.companyId, // 必传：当前公司ID
					itemType: 1, // 默认收入项（后端必填）
					dataType: 1, // 默认固定金额（后端必填）
					sortOrder: this.salaryFields.length + 10, // 排序号默认在最后
					fixedAmount: null,
					ratio: null,
					baseSource: null,
					remark: `自定义工资项`
				};

				try {
					let res;
					if (this.currentField.id) {
						// 编辑操作：PUT请求
						formData.id = this.currentField.id;
						res = await this.http.put('/VipSalaryItem', formData);
					} else {
						// 新增操作：POST请求
						res = await this.http.post('/VipSalaryItem', formData);
					}

					// 适配后端响应格式（code=200为成功）
					if (res.code === 200) {
						uni.showToast({
							title: '操作成功',
							icon: 'success'
						});
						this.closePopup();
						this.getSalaryFields(); // 重新加载列表
					} else {
						uni.showToast({
							title: '操作失败：' + (res.msg || '未知错误'),
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('保存工资项失败', error);
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					});
				}
			},

			// 删除工资项（统一用this.http，传递公司ID）
			async deleteField(id) {
				const field = this.salaryFields.find(item => item.id === id);
				uni.showModal({
					title: '确认删除',
					content: `确定要删除【${field.fieldName}】吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								const res = await this.http.delete(`/VipSalaryItem/${id}`, {
									params: {
										companyId: this.companyId
									} // 传递公司ID
								});
								// 适配后端响应格式
								if (res.code === 200) {
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									});
									this.getSalaryFields(); // 重新加载列表
								} else {
									uni.showToast({
										title: '删除失败：' + (res.msg || '未知错误'),
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('删除工资项失败', error);
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			// 切换启用状态（统一用this.http，传递公司ID）
			async handleStatusChange(id) {
				const field = this.salaryFields.find(item => item.id === id);
				if (field) {
					try {
						await this.http.put('/VipSalaryItem', {
							id: field.id,
							isEnabled: field.isEnabled ? 1 : 0,
							// 其他必填字段（保持原有值，确保后端校验通过）
							itemName: field.fieldName,
							isSystem: field.fieldType,
							companyId: this.companyId,
							itemType: 1,
							dataType: 1,
							sortOrder: this.salaryFields.findIndex(item => item.id === id) + 1,
							fixedAmount: null,
							ratio: null,
							baseSource: null
						});
						uni.showToast({
							title: '状态更新成功',
							icon: 'success'
						});
					} catch (error) {
						console.error('更新状态失败', error);
						// 失败时回滚状态
						field.isEnabled = !field.isEnabled;
						uni.showToast({
							title: '更新失败',
							icon: 'none'
						});
					}
				}
			},

			// 关闭弹窗（保持原有逻辑）
			closePopup() {
				this.showFieldDialog = false;
				this.currentField = {
					fieldName: '',
					isEnabled: true,
					fieldType: 2
				};
			},

			// 空方法（保持原有结构）
			openPopup() {}
		}
	};
</script>

<style scoped>
	.page-container {
		min-height: 100vh;
		background-color: #f5f9fc;
		padding: 0 15px;
		padding-bottom: 80px;
		box-sizing: border-box;
	}

	.navbar-left .nav-back-content {
		display: flex;
		align-items: center;
	}

	.navbar-left .nav-title {
		color: #1e88e5;
		font-size: 17px;
		margin-left: 8px;
	}

	.config-desc {
		padding: 15px;
		margin: 15px 0;
		font-size: 14px;
		color: #6b7280;
		background-color: #e6f7ff;
		border-radius: 8px;
		line-height: 1.5;
	}

	/* 列表样式：两行显示+上下间距 */
	.field-list {
		background-color: #ffffff;
		border-radius: 10px;
		padding: 15px 0;
		margin-bottom: 20px;
	}

	.field-item {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		/* 顶部对齐，实现两行显示 */
		padding: 12px 15px;
		margin: 8px 10px;
		/* 上下间距8px，左右间距10px */
		background-color: #f9fafb;
		border-radius: 8px;
	}

	.field-info {
		flex: 1;
		padding-top: 2px;
	}

	.field-name {
		font-size: 16px;
		color: #333;
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		/* 自动换行，实现两行显示 */
	}

	.field-tag {
		font-size: 12px;
		color: #409eff;
		background-color: #e6f7ff;
		padding: 2px 8px;
		border-radius: 12px;
		margin-left: 10px;
		margin-top: 4px;
		/* 换行后顶部间距 */
		display: inline-flex;
		align-items: center;
		gap: 3px;
	}

	.custom-tag {
		color: #27ae60;
		background-color: #f0fdf4;
	}

	.field-actions {
		display: flex;
		align-items: center;
		gap: 15px;
	}

	.action-icons {
		display: flex;
		gap: 15px;
	}

	.add-btn-container {
		position: fixed;
		bottom: 20px;
		left: 0;
		right: 0;
		display: flex;
		justify-content: center;
		padding: 0 30px;
		box-sizing: border-box;
	}

	.add-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8px;
		width: 100%;
		padding: 14px 0;
		background-color: #1E88E5;
		color: #ffffff;
		border-radius: 50px;
		font-size: 16px;
		box-shadow: 0 4px 15px rgba(30, 136, 229, 0.4);
	}

	.add-btn-text {
		font-weight: 500;
	}

	.popup-content {
		padding: 30px 25px;
		background-color: #ffffff;
		width: 85%;
		max-width: 500px;
		box-sizing: border-box;
	}

	.popup-title {
		font-size: 18px;
		color: #333;
		font-weight: 500;
		margin-bottom: 30px;
		text-align: center;
	}

	.form-container {
		margin-bottom: 35px;
	}

	/* 标签和输入框同行样式 */
	.form-item {
		display: flex;
		align-items: center;
		gap: 15px;
		margin-bottom: 25px;
	}

	.form-label {
		font-size: 15px;
		color: #333;
		width: 80px;
		text-align: right;
		flex-shrink: 0;
	}

	/* 输入框仅下边框 */
	.form-input {
		flex: 1;
		padding: 10px 0;
		border: none;
		border-bottom: 1px solid #e5e7eb;
		/* 仅下边框 */
		border-radius: 0;
		font-size: 15px;
		background-color: transparent;
	}

	.form-input:focus {
		outline: none;
		border-bottom-color: #1E88E5;
		/* 聚焦时下边框变色 */
		box-shadow: none;
	}

	.popup-actions {
		display: flex;
		gap: 15px;
	}

	.btn-cancel {
		flex: 1;
		padding: 13px 0;
		background-color: #f5f5f5;
		color: #333;
		border-radius: 8px;
		font-size: 15px;
		text-align: center;
	}

	.btn-submit {
		flex: 1;
		padding: 13px 0;
		background-color: #1E88E5;
		color: #fff;
		border-radius: 8px;
		font-size: 15px;
		text-align: center;
	}
</style>